//
//  TXMaskView.swift
//  swiftTXH
//
//  Created by Mac mini on 2020/9/10.
//  Copyright © 2020 Mac mini. All rights reserved.
//

import UIKit

public class CNMMaskView: UIView {
    
    public static let shared = CNMMaskView()
    
    // MARK: - UI
    private var childView: UIView?
    private lazy var bgWindow: UIWindow? = self.createWindow()
    
    // MARK: - Datasource
    private var dismissBlock: (()->Void)?
    
    // MARK: - Life Cycle
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension CNMMaskView: UIGestureRecognizerDelegate {
    @objc private func cnm_tapWindowAction() {
        dimiss(self.dismissBlock)
    }
    
    public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if touch.view == self.bgWindow {
            return true
        }
        return false
    }
}

extension CNMMaskView {
    public final func show(childView: UIView) {
        self.childView = childView
        
        if bgWindow == nil {
            bgWindow = createWindow()
        }

        bgWindow?.addSubview(childView)
        bgWindow?.becomeKey()
        
        UIView.animate(withDuration: 0.25, delay: 0, options: [.curveLinear, .beginFromCurrentState], animations: {
            self.bgWindow?.isHidden = false
            self.bgWindow?.alpha = 1.0
            self.bgWindow?.makeKeyAndVisible()
        })
    }
    
    public final func dimiss(_ block: (()->Void)? = nil) {
        self.bgWindow?.resignKey()
        
        UIView.animate(withDuration: 0.25, delay: 0, options: [.curveLinear, .beginFromCurrentState], animations: {
            self.bgWindow?.alpha = 0.0
        }, completion: { _ in
            self.bgWindow?.isHidden = true
            self.childView?.removeFromSuperview()
            self.childView = nil
            self.bgWindow = nil
            
            if let block = block {
                block()
            }
        })
    }
    
    private func createWindow() -> UIWindow? {
        var window: UIWindow?
        
        if #available(iOS 13.0, *) {
            let windowScene = UIApplication.shared
                            .connectedScenes
                            .filter { $0.activationState == .foregroundActive }
                            .first
            if let windowScene = windowScene as? UIWindowScene {
                // 该window是全局变量
                window = UIWindow(windowScene: windowScene)
                window?.frame = UIScreen.main.bounds
                window?.windowLevel = UIWindow.Level.alert
            }
        } else {
            window = UIWindow(frame: UIScreen.main.bounds)
            // 显示优先级, 通常会有三个值, 优先级顺序为: UIWindowLevelAlert > UIWindowLevelStatusBar > UIWindowLevelNormal
            window?.windowLevel = .alert
        }
        window?.backgroundColor = UIColor(white: 0, alpha: 0.35)
        window?.isHidden = true
        window?.alpha = 0.0
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(cnm_tapWindowAction))
        tap.delegate = self
        window?.addGestureRecognizer(tap)
        
        return window
    }
}


